package se.vgregion.icc;

import org.springframework.beans.factory.config.BeanPostProcessor;

import se.vgregion.icc.handlers.PingHandler;
import se.vgregion.icc.handlers.ResponseHandler;

/***
 * BeanPostProcessor used to register PingHandlers upon creation.<br/>
 * 
 * @author ricra2 & andan40
 * @see {@link org.springframework.beans.factory.config.BeanPostProcessor}
 */
public final class RegisterHandlerBeanPostProcessor implements BeanPostProcessor {

    private PingHandlerRegistry pingHandlerRegistry;
    private ResponseHandlerRegistry responseHandlerRegistry;

    private RegisterHandlerBeanPostProcessor(PingHandlerRegistry pingHandlerRegistry,
        ResponseHandlerRegistry responseHandlerRegistry) {
        this.pingHandlerRegistry = pingHandlerRegistry;
        this.responseHandlerRegistry = responseHandlerRegistry;
    }

    /***
     * {@inheritDoc}
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean;
    }

    /***
     * <p>Added implementation: If the bean is of the type PingHandler, 
     * it will register itself to PingHandlerRegistry.</p>
     * {@inheritDoc}
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if (bean instanceof PingHandler) {
            PingHandler handler = (PingHandler) bean;
            pingHandlerRegistry.addPingHandlerImplementation(handler.getHandledDependencyClass(), handler);
        } else if (bean instanceof ResponseHandler) {
            ResponseHandler handler = (ResponseHandler) bean;
            responseHandlerRegistry.addPingHandlerImplementation(handler.getHandledClassTagName(), handler);
        }
        return bean;
    }
}
